import React from 'react';
import { Table, Modal, TableProps, message, Image } from 'antd';
import dayjs from 'dayjs';
import _ from 'lodash';
import cash from 'cash-dom';
import utils, { findText } from '@/utils';
import { TOWN_NATURE } from '@/constant/schoolOptions';

const columns: TableProps['columns'] = [
  {
    title: '变更信息',
    width: 100,
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '变更前',
    width: 100,
    dataIndex: 'beforValue',
    key: 'beforValue',
    align: 'center',
    render: (text, record) => {
      if (utils.isImage(record.beforAttach)) {
        return <Image src={record.beforAttach} alt="" style={{ width: 100, height: 100 }} />;
      }

      if (record.key === 'school.urban_rural_nature') {
        const ret = [];
        record.beforAttach?.forEach(item => {
          ret.push(findText(TOWN_NATURE, item));
          ret.push('/');
        });
        ret.pop();
        return ret;
      }
      return text;
    },
  },
  {
    title: '变更后',
    width: 100,
    dataIndex: 'afterValue',
    key: 'afterValue',
    align: 'center',
    render: (text, record) => {
      if (utils.isImage(record.afterAttach)) {
        return <Image src={record.afterAttach} alt="" style={{ width: 100, height: 100 }} />;
      }
      if (record.key === 'school.urban_rural_nature') {
        const ret = [];
        record.afterValue?.forEach(item => {
          ret.push(findText(TOWN_NATURE, item));
          ret.push('/');
        });
        ret.pop();
        return ret;
      }
      return text;
    },
  },
];
// eslint-disable-next-line react/require-default-props
const Groups: React.FC<{
  show: boolean;
  onCancel: () => void;
  onOk: () => void;
  beforValue: any;
  form: any;
  template: any[];
}> = ({ show = true, onCancel, onOk, beforValue, form, template }) => {
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [showModal, setShowModal] = React.useState(false);

  const changeSave = () => {
    const find = (key: any) => {
      for (let i = 0; i < template.length; i++) {
        const cnt = _.find(template[i].inputs, { name: key });
        if (cnt) {
          return cnt;
        }
      }
      return { label: key };
    };
    const getval = (cnt, val) => {
      if (typeof val === 'object' && val.length === 1 && val[0].uid) {
        return val[0].uid;
      }
      if (val?.isValid) {
        if (cnt.inputProps.picker === 'month') {
          return dayjs(val).format('YYYY-MM');
        }
        if (cnt.inputProps.picker === 'year') {
          return dayjs(val).format('YYYY');
        }
        return dayjs(val).format('YYYY-MM-DD');
      }
      if (cnt.renderOption && cnt.renderOption.length && cnt.inputType === 'select') {
        return _.find(cnt.renderOption, { value: val })?.label;
      }
      if (cnt.renderOption && cnt.renderOption.length && cnt.inputType === 'children') {
        const arr: any[] = [];
        if (_.isArray(val)) {
          val.forEach(v => {
            const label = utils.findLabelDeep(cnt.renderOption, String(v));
            if (label) {
              arr.push(label);
            }
          });
        }
        return arr.join('/');
      }
      return val;
    };
    const getattach = (cnt, val) => {
      if (typeof val === 'object' && val.length === 1 && val[0].url) {
        return val[0].url;
      }
      return '';
    };
    return () => {
      form
        .validateFields()
        .then(newVals => {
          const changelist = [];
          for (const key in newVals) {
            if ((newVals[key] || typeof newVals[key] === 'boolean') && newVals[key] !== beforValue[key]) {
              const cnt = find(key);
              changelist.push({
                key,
                name: cnt.label,
                beforAttach: beforValue[key],
                afterAttach: getattach(cnt, newVals[key]),
                beforValue: getval(cnt, beforValue[key]),
                afterValue: getval(cnt, newVals[key]),
              });
            }
          }
          if (changelist.length > 0) {
            setDataSource(changelist);
            setShowModal(true);
          } else {
            message.info('无内容变更', 1, () => {
              onCancel();
            });
          }
        })
        .catch(errors => {
          //console.log(errors);
          const firstErrorField = errors?.errorFields[0].name[0];
          const _cash = cash;
          _cash(`[for="${firstErrorField}"]`).closest(`.expend`).removeClass('expend');
          form.scrollToField(firstErrorField);
          document.querySelector('.ant-layout-content').scrollTop -= 80;
          onCancel();
        });
    };
  };
  React.useEffect(() => {
    if (show) {
      changeSave()();
    } else setShowModal(false);
  }, [show]);
  return (
    <Modal
      open={showModal}
      title="变更记录"
      width="50%"
      okText="保存"
      cancelText="返回"
      onOk={onOk}
      onCancel={onCancel}
    >
      <Table columns={columns} dataSource={dataSource} pagination={{ pageSize: 5 }} scroll={{ x: 'max-content' }} />
    </Modal>
  );
};

export default Groups;
